<?php

namespace App\Http\Controllers\Service\Visit;

use App\Http\Controllers\ApiController;
use App\Http\Controllers\Common\YouzanOrderController;
use App\Http\Requests\Service\Visit\AppScanProductRequest;
use App\Models\Panx\Product;
use App\Models\Panx\Visit;

class AppScanProductController extends ApiController
{
    const ROUTES = [
        'invoke'   => 'service.scan-product-convert.invoke',
    ];

    /**
     * @param AppScanProductRequest $request
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function __invoke(AppScanProductRequest $request)
    {
        $prod_id = $request->product_id;
        $dev_acnt_id = $request->device_account_id;

        /** @var Product $prod */
        $prod = (new Product)->find($prod_id);
            $this->checkItemExist($prod, 'product');

        if ($prod->youzan_item_id) {
            $redirect = YouzanOrderController::routeRedirectUrl($prod_id, $dev_acnt_id);
        } else {
            $this->checkCanOperate($prod->product_url, 'product url');
            $redirect = $prod->product_url;
        }

        Visit::createAppScanProduct($prod->id, $dev_acnt_id);

        // 302 redirect
        return redirect($redirect);
    }
}
